package com.joysuch.wwyt.edu.schedule;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.joysuch.wwyt.config.RedisClient;
import com.joysuch.wwyt.edu.bean.EduDoExamResultBean;
import com.joysuch.wwyt.edu.service.EduExamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RScoredSortedSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ExamSubmitSchedule {

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private EduExamService eduExamService;


    @Scheduled(cron = "* * * * * ?")
    public void task() {
        String key = "CACHE_EXAM_TASK";
        RScoredSortedSet<String> zSet = redisClient.getZSet(key);
        if (CollectionUtil.isNotEmpty(zSet)) {
            for (String v : zSet) {
                // v = examId + "-" + userId
                String[] split = v.split("-");
                Long examId = Long.valueOf(split[0]);
                Long userId = Long.valueOf(split[1]);

                EduDoExamResultBean eduDoExamResultBean = new EduDoExamResultBean();
                eduDoExamResultBean.setId(examId);
                // 3 获取
                String json = eduExamService.cacheAnswers(eduDoExamResultBean, userId, 3);
                if (StringUtils.isEmpty(json)) {
                    continue;
                }
                EduDoExamResultBean bean = JSONUtil.toBean(json, EduDoExamResultBean.class);
                if (bean.getIsSubmit() == 0) {
                    // 考试结束时间
                    long examEntTime = redisClient.getZSetScore(key, v);
                    // 当前时间
                    long now = DateUtil.current();
                    // 如果当前时间大于 考试结束时间 则执行 提交逻辑
                    if (now > examEntTime) {
                        log.info("--------------------检测考试到时定时 检测到 考试id{},用户id{},到时自动提交试卷--------------------", examId, userId);
                        EduDoExamResultBean.ExamResult examResult = eduExamService.submit(bean, userId,1);
                        bean.setIsSubmit(3);
                        bean.setExamResult(examResult);
                        eduExamService.cacheAnswers(bean, userId, 2);
                        redisClient.removeZSet(key, v);

                    }
                }

            }
        }

    }
}
